//
//  FMPlayerView.m
//  NewMyMusicAPP
//
//  Created by 11_wyq on 15/6/21.
//  Copyright (c) 2015年 lanou3g.com 蓝鸥科技. All rights reserved.
//

#import "FMPlayerView.h"
#import "FMPersonModel.h"

@interface FMPlayerView ()

{
    UIButton *yinbutton;
    UISlider * progress;
    //音量隐藏
    UIButton *_yinbutton;
    UISlider* _volumeSlider;
    UILabel *_currentPlaybackTime;
    UILabel * _totalPlaybackTime;
    UILabel *_tishi;
}

@property (nonatomic, retain)NSTimer *mytime;

@end

@implementation FMPlayerView




-(instancetype)initWithFrame:(CGRect)frame array:(NSMutableArray *)array
{
    self = [super initWithFrame:frame];
    if (self) {
        
        [self createSubviews:array];
        
        //设置BOOL初始值为NO
        _isPlaying = YES;
        _isRotating = YES;
        
        self.playViewArray = [NSMutableArray array];
        
    }
    return self;
    
}

-(void)createSubviews:(NSMutableArray *)array
{
#pragma mark -- 获得数组
    
    [self.playViewArray addObjectsFromArray:array];
    
    self.backgroundColor = [UIColor blackColor];

    
    //背景图片
    self.MyImageView = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, MYWIDTH, MYHEIGHT)];
    [self addSubview:self.MyImageView];
    [_MyImageView release];
    _MyImageView.backgroundColor = [UIColor blackColor];
    _MyImageView.userInteractionEnabled = YES;//打开用户交互
    _MyImageView.image = [UIImage imageNamed:@"backGround.jpg"];
    
////    //图片毛玻璃效果
//    UIVisualEffectView *visualEfView = [[UIVisualEffectView alloc] initWithEffect:[UIBlurEffect effectWithStyle:UIBlurEffectStyleLight]];
//    visualEfView.frame = _MyImageView.frame;
//    visualEfView.alpha = 1.0;
//    [_MyImageView addSubview:visualEfView];
//    
    
    
    //旋转图片
    _image = [[UIImageView alloc]initWithFrame:CGRectMake(90 * WIDTH, 150 * HEIGHT, 230 * WIDTH, 230 * WIDTH)];
    _image.backgroundColor = [UIColor blackColor];
    [_MyImageView addSubview:_image];
    [_image release];
    _image.layer.masksToBounds = YES;//设置圆角边缘
    _image.clipsToBounds = YES;
    _image.layer.cornerRadius = _image.frame.size.height / 2;//设置弧度
    _image.image = [UIImage imageNamed:@"B1.jpg"];
    
//     _image.image = [UIImage imageNamed:@"roll.png"];
    _image.center = CGPointMake(190 * WIDTH  ,200 * WIDTH  );
    
    
// 播放按钮
    _button = [UIButton buttonWithType:UIButtonTypeCustom];
    _button.frame = CGRectMake(140 * WIDTH, 380 * HEIGHT , 80 * WIDTH , HEIGHT * 80);
    _button.backgroundColor = [UIColor clearColor];
    [_button setBackgroundImage:[UIImage imageNamed:@"toolbar_pause_n@2x.png"] forState:UIControlStateNormal];
    [_button addTarget:self action:@selector(playButtonAction) forControlEvents:UIControlEventTouchUpInside];
    [_MyImageView addSubview:_button];
    
    
// 上一曲
    UIButton *leftButton = [UIButton buttonWithType:UIButtonTypeCustom];
    leftButton.frame = CGRectMake(50 * WIDTH,390 * HEIGHT, 60 * WIDTH, 60 * HEIGHT);
    [_MyImageView addSubview:leftButton];
    leftButton.backgroundColor = [UIColor clearColor];
    [leftButton setBackgroundImage:[UIImage imageNamed:@"toolbar_prev_n@2x.png"] forState:UIControlStateNormal];
    [leftButton addTarget:self action:@selector(leftButtonAction) forControlEvents:UIControlEventTouchUpInside];
    
// 下一曲按钮
    UIButton *rightButton = [UIButton buttonWithType:UIButtonTypeCustom];
    rightButton.frame = CGRectMake(240 * WIDTH ,390 * HEIGHT, 60 * WIDTH, 60 * HEIGHT);
    [_MyImageView addSubview:rightButton];
    rightButton.backgroundColor = [UIColor clearColor];
    [rightButton setBackgroundImage:[UIImage imageNamed:@"toolbar_next_n@2x.png"] forState:UIControlStateNormal];
    [rightButton addTarget:self action:@selector(rightButtonAction) forControlEvents:UIControlEventTouchUpInside];
    
    
    //音量按钮
    
    _yinbutton=[UIButton buttonWithType:UIButtonTypeCustom];
    _yinbutton.frame = CGRectMake(320*OffWidth, 400, 40, 40);
    [_yinbutton setImage:[UIImage imageNamed:@"shengyin.png"] forState:UIControlStateNormal];
    [_yinbutton addTarget:self action:@selector(hidden:) forControlEvents:UIControlEventTouchUpInside];
    [self addSubview:_yinbutton];
    
    
    //声音控件
    _volumeSlider= [[UISlider alloc] initWithFrame:CGRectMake(40, 40, 300, 40)];
    _volumeSlider.maximumValue = 10;
    _volumeSlider.minimumValue = 0;
    _volumeSlider.minimumTrackTintColor = [UIColor colorWithHexString:@"00FF00"];
    _volumeSlider.maximumTrackTintColor = [UIColor lightGrayColor];
//    [_volumeSlider setThumbImage:[UIImage imageNamed:@"yuan"] forState:UIControlStateNormal];
//    _volumeSlider.value = 2;
    _volumeSlider.hidden = YES;
    [_volumeSlider addTarget:self action:@selector(volumeSet:) forControlEvents:UIControlEventValueChanged];
//    _volumeSlider.transform =CGAffineTransformMakeRotation(- 90* M_PI/180);
    [self addSubview:_volumeSlider];
    

    
    
    //开始时间
    _currentPlaybackTime = [[UILabel alloc] initWithFrame:CGRectMake(5,self.frame.size.height-130*OffHeight , 50, 25)];
    _currentPlaybackTime.font =[UIFont boldSystemFontOfSize:14.0f];
    _currentPlaybackTime.textAlignment = NSTextAlignmentCenter;
    _currentPlaybackTime.textColor = [UIColor blackColor];
    _currentPlaybackTime.text = @"00:00";
    [self addSubview:_currentPlaybackTime];
    
    
    //总长时间
    _totalPlaybackTime = [[UILabel alloc] initWithFrame:CGRectMake(self.frame.size.width-53, self.frame.size.height-130 , 50, 25)];
    
    _totalPlaybackTime.font =[UIFont boldSystemFontOfSize:14.0f];
    _totalPlaybackTime.textAlignment = NSTextAlignmentCenter;
    _totalPlaybackTime.textColor = [UIColor blackColor];
    _totalPlaybackTime.text = @"00:00";
    [self addSubview:_totalPlaybackTime];
    
    
    //进度条
    progress = [[UISlider alloc]initWithFrame:CGRectMake(10,self.frame.size.height-150, self.frame.size.width -20 , 5)];
    progress.continuous = YES;
    progress.backgroundColor=[UIColor blueColor];
    progress.minimumTrackTintColor = [UIColor cyanColor];
    progress.maximumTrackTintColor = [UIColor whiteColor];
    [progress addTarget:self action:@selector(PlaySlider:) forControlEvents:UIControlEventValueChanged];
    progress.value = _audioPlayer.progress;
    [progress setThumbImage:[UIImage imageNamed:@"yuan.png"] forState:UIControlStateNormal];
    [self addSubview:progress];
    _tishi=[[UILabel alloc]initWithFrame:CGRectMake(self.frame.size.width/2-30, self.frame.size.height-150, self.frame.size.width/3, 40)];
    _tishi.textColor = [UIColor colorWithHexString:@"FFFFFF"];
    [self addSubview:_tishi];
    
    //定时器
    self.mytime=[NSTimer scheduledTimerWithTimeInterval:1.f target:self selector:@selector(startPlayTimeCount) userInfo:nil repeats:YES];
  

    
    [self spinOn];
    
}

// 进度条
-(void)PlaySlider:(id)sender{
    
    if (_audioPlayer) {
        
        UISlider * processSlider = sender;
        [_audioPlayer seekToTime:processSlider.value];
        
    }
    
}
//音量隐藏
-(void)hidden:(UIButton *)button
{
   if (button.selected == NO){
    button.selected = YES;
    [_volumeSlider setHidden:NO];
    
}
 else
 {
    [_volumeSlider setHidden:YES];
    button.selected = NO;
  }
    
    
}

//音量设置
-(void)volumeSet:(UISlider*)slider
{
    _audioPlayer.volume = slider.value;
}

//显示时间
- (void)startPlayTimeCount
{
    if (progress) {
        
        progress.maximumValue = _audioPlayer.duration;
        progress.value = _audioPlayer.progress;
        NSInteger proMinute = (NSInteger)_audioPlayer.progress / 60;
        NSInteger proSecond = (NSInteger)_audioPlayer.progress % 60;
        NSInteger durMinute = (NSInteger)_audioPlayer.duration / 60;
        NSInteger durSecond = (NSInteger)_audioPlayer.duration % 60;
        
        _currentPlaybackTime.text = [NSString stringWithFormat:@"%02ld:%02ld", (long)proMinute, (long)proSecond];
        _totalPlaybackTime.text=[NSString stringWithFormat:@"%02ld:%02ld" , (long)durMinute, (long)durSecond];
        _tishi.text = _audioPlayer.state == STKAudioPlayerStateBuffering ? @"缓冲中..." : @"";
        
    }
}



-(void)setModel:(FMPlayerModel *)model
{
    if (_model != model) {
        [_model release];
        _model = [model retain];
    }
    
      //将url转成image
    NSURL *imageUrl = [NSURL URLWithString:[model.images firstObject]];
    //创建系统的全局队列(子线程)
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
       
        NSData *data = [NSData dataWithContentsOfURL:imageUrl];
        
        dispatch_async(dispatch_get_main_queue(), ^{
           
            UIImage *image = [UIImage imageWithData:data];
        });
        
    });
    
    [_image sd_setImageWithURL:imageUrl placeholderImage:[UIImage imageNamed:@"B1.jpg"]];
    
    
    
}




#pragma mark -- 播放时旋转
-(void)playButtonAction
{
    
     if (_isPlaying == YES && _isRotating == YES) {
        
         [self stopRotate];
        
        _isPlaying = YES;
        _isRotating = NO;
        [_button setBackgroundImage:[UIImage imageNamed:@"toolbar_play_n@2x.png"] forState:UIControlStateNormal];
        
        [_audioPlayer pause];//暂停
        
    }else if(_isPlaying == YES && _isRotating == NO)
    {
    
        [self ContinueToRotate];//继续旋转
        _isPlaying = YES;
        _isRotating = YES;
        [_button setBackgroundImage:[UIImage imageNamed:@"toolbar_pause_n@2x.png"] forState:UIControlStateNormal];
        [_audioPlayer resume];//继续播放
        
        
        
    }    
   
   
    
}



#pragma mark -- 设置图片旋转
-(void)spinOn//开始旋转
{
    CABasicAnimation *basicAnimation = [CABasicAnimation animationWithKeyPath:@"transform.rotation.z"];//设置Z轴
    [basicAnimation setFromValue:[NSNumber numberWithInt:0]];//设置动画初始值
    [basicAnimation setToValue:[NSNumber numberWithInt:M_PI * 2]];//设置动画结束
    [basicAnimation setDuration:10];//设置动画时长
    [basicAnimation setRepeatCount:FLT_MAX];//无限旋转
    [basicAnimation setAutoreverses:NO];//动画结束后是否回到原来状态
    [basicAnimation setCumulative:YES];//累加 追加动画,不会出现结束后卡顿的现象,在上一次结束的地方继续开始
    [self.image.layer addAnimation:basicAnimation forKey:@"basicA"];
    
}

#pragma mark -- 图片旋转暂停
-(void)stopRotate//旋转暂停
{
    [UIView animateWithDuration:0.1 delay:0 options:UIViewAnimationOptionCurveEaseInOut
                     animations:^{
                         
                     }
        completion:^(BOOL finished){
    if (finished){
            [UIView animateWithDuration:1.0 animations:^{
                                 //pause
            CFTimeInterval pausedTime = [_image.layer convertTime:CACurrentMediaTime() fromLayer:nil];
                                 //时间停止
            _image.layer.speed = 0.0;
                                 //记录你停止的时间
        _image.layer.timeOffset = pausedTime;
                
            }];
        
        }
            
    }];
}

#pragma mark -- 图片继续旋转
-(void)ContinueToRotate
{
     //停止的时间
    CFTimeInterval pausedTime = [self.image.layer timeOffset];
  
    self.image.layer.speed = 1.0;
    self.image.layer.timeOffset = 0.0;
    self.image.layer.beginTime = 0.0;
    //用一共的时间 减去停止的时间
    CFTimeInterval timeSincePause = [self.image.layer convertTime:CACurrentMediaTime() fromLayer:nil] - pausedTime;
    //是暂停过后开始的时间
    self.image.layer.beginTime = timeSincePause;

}

-(void)Recovery
{
    
    CABasicAnimation *basicAnimation = [CABasicAnimation animationWithKeyPath:@"transform.rotation.z"];//设置Z轴
    [basicAnimation setFromValue:[NSNumber numberWithInt:0]];//设置动画初始值
     [self.image.layer addAnimation:basicAnimation forKey:@"basicA"];
    
}

#pragma mark -- 左边按钮  跳到上一首
-(void)leftButtonAction
{
    [self.myDelegate lastSong];
}

#pragma mark -- 右边按钮  跳到下一首
-(void)rightButtonAction
{
    [self.myDelegate NextMusic];
    
}





@end
